package com.wl.shixun3.controller;

import com.wl.shixun4.util.SessionManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登出控制器
 */
@WebServlet("/shixun3/logout")
public class LogoutController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        handleLogout(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        handleLogout(request, response);
    }

    private void handleLogout(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 获取当前会话
        HttpSession session = request.getSession(false);
        
        if (session != null) {
            // 获取用户名
            String username = (String) session.getAttribute("username");
            
            // 从SessionManager中移除会话
            if (username != null) {
                SessionManager.removeSession(username);
            }
            
            // 销毁会话
            session.invalidate();
        }
        
        // 重定向到登录页面
        response.sendRedirect(request.getContextPath() + "/shixun3/login.jsp?message=loggedOut");
    }
}

